import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:test_app/core/utils/aletr/alert_util.dart';
import 'package:test_app/core/utils/common/common_util.dart';
import 'package:test_app/core/utils/storage/storage_util.dart';

class PermissionUtil {

  static bool get isIos => CommonUtil.isIos();

  static Future<bool> getStoragePermission() async {
    late PermissionStatus myPermission;

    /// 读取系统权限
    if (isIos) {
      myPermission = await Permission.photosAddOnly.request();
    } else {
      myPermission = await Permission.storage.request();
    }

    debugPrint('PermissionUtil -> current status: $myPermission');

    if (myPermission != PermissionStatus.granted) {
      if (!_isFirstVisit('photosAddOnly')) {
        _openSetting('相册');
      }
      return false;
    } else {
      return true;
    }
  }

  static bool _isFirstVisit(String name) {
     final Map<String, dynamic> permission = StorageUtil.getObject('permission');
     if (permission.containsKey(name)) return false;
     permission[name] = true;
     StorageUtil.setObject('permission', permission);
     return true;
  }

  static void _openSetting(String name) {
    AlertUtil.showConfirmDialog('是否前往设置页面开启$name权限', title: '当前权限被永久拒绝', rightBtnAction: openAppSettings);
  }

}
